

import { Component, OnInit } from '@angular/core';
import { NavController, ToastController, ModalController } from '@ionic/angular';
import { Keyboard } from '@ionic-native/keyboard/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { GlobalService } from '@services/global.service';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';
import { ADModal } from '@modals/ad-modal/ad-modal';
import { Router } from '@angular/router';
// import { TabsPage } from '../tabs.page';
import { forkJoin } from 'rxjs';
import { UserInfoModal } from '@modals/user-info/user-info';
import { LoadingService } from '@services/loading.service';
import { JPush } from '@jiguang-ionic/jpush/ngx';

declare var window;
@Component({
  selector: 'page-login',
  // providers: [],
  templateUrl: 'login.html',
  styleUrls: ['login.scss']
})

export class LoginPage implements OnInit {
  load; // 数据加载动画
  MORNING_START_TIME = 5;
  NOON_START_TIME = 9;
  NIGHT_START_TIME = 18;

  companyName = '@' + new Date().getFullYear() + '能效通建筑物联网';
  companyUrl = 'www.nxtone.net';

  phoneLogin = false;
  user = {
    username: '',
    password: '',
  };
  sms = {
    cellphone: '',
    smscode: '',
  };
  error = '';
  showError = false;

  timeNow = 'noon';
  keyboardStatus = 'hide';
  getSMSCodeText = '获取验证码';
  couldSendSMSCode = true;

  constructor(
    public global: GlobalService,
    public cache: CacheService,
    public dataservice: DataService,
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    // public navParams: NavParams,
    public modalCtrl: ModalController,
    public keyboard: Keyboard,
    public statusBar: StatusBar,
    public router: Router,
    public loadService: LoadingService,
    public jpush: JPush
  ) {
    this.calculateBG();
    // this.statusBar.hide();
    // this.statusBar.overlaysWebView(true);
  }

  ngOnInit() {
    console.log('hello `login` component');
    if (this.cache.userinfo) {
      this.user.username = this.cache.userinfo.account;
      this.user.password = this.cache.upwd;
    }

    window.addEventListener('keyboardWillShow', (event) => {
      // Describe your logic which will be run each time when keyboard is about to be shown.
      this.keyboardStatus = 'show';
    });

    window.addEventListener('keyboardWillHide', (event) => {
      // Describe your logic which will be run each time when keyboard is about to be closed.
      this.keyboardStatus = 'hide';
    });
  }

  ionViewWillEnter() {
    console.log('进入login');
    this.statusBar.show();
    this.statusBar.overlaysWebView(true);
  }

  calculateBG() {
    const datetime = new Date();
    const hour = datetime.getHours();
    this.timeNow = 'night';
    if (hour >= this.MORNING_START_TIME && hour < this.NOON_START_TIME) {
      this.timeNow = 'morning';
    }
    if (hour >= this.NOON_START_TIME && hour < this.NIGHT_START_TIME) {
      this.timeNow = 'noon';
    }
  }

  /**
   * 登录
   */
  public doLogin(): void {
    this.load = this.loadService.load(null);
    if (this.phoneLogin) {
      this.loginWithSMSCode();
    } else {
      this.loginWithUsernamePWD();
    }
  }

  /**
   * 使用用户名密码登录
   */
  async loginWithUsernamePWD() {
    this.dataservice.login(this.user).subscribe((data) => {
      if (data.success) {
        setTimeout(() => {
          this.load.then(res => {
            res.dismiss();
            this.load = null;
            this.initData(data);
          })
        }, 2000)
      } else {
        setTimeout(() => {
          this.load.then(res => {
            res.dismiss();
            this.load = null;
            if (data.message.length > 40) {
              this.error = data.message.substring(0, 41) + '...';
            } else {
              this.error = data.message;
            }
            if (data.code === 409) {
              console.log('错误');
              this.showError = true;
              this.cache.upwd = this.user.password;
            } else {
              this.showError = false;
            }
          })
        }, 2000);
      }
    });
  }

  /**
   * 使用短信验证码登录
   */
  loginWithSMSCode() {
    if (this.verifyCellphone(this.sms.cellphone)) {
      this.dataservice.loginWithSMSVerifyCode(this.sms.cellphone, this.sms.smscode).subscribe(ret => {
        if (ret.success) {
          // 成功登录
          this.initData(ret);
        } else {
          setTimeout(() => {
            this.load.then(res => {
              res.dismiss();
              this.load = null;
              if (ret.message.length > 40) {
                this.error = ret.message.substring(0, 41) + '...';
              } else {
                this.error = ret.message;
              }
            });
          }, 2000)
        }
      });
    }
  }

  /**
   * 登录初始化
   * @param data 后台返回数据
   */
  initData(data) {
    this.cache.clientToken = data.data;
    this.cache.upwd = this.user.password;
    this.global.isLogin = true;
    this.dataservice.setHeader();

    const userData = this.dataservice.getUserInfo();
    const functionData = this.dataservice.getFunctions(null);
    const companyData = this.dataservice.getCompanyInfo();

    forkJoin([userData, functionData, companyData]).subscribe(results => {
      const user: any = results[0];
      this.cache.functionPoint = results[1].data;
      this.cache.companys = results[2].data;
      if (user.success) {
        console.log(user);
        console.log(this.global.isLogin);
        const result = JSON.parse(JSON.stringify(user.data));
        const userInfo = result;
        this.cache.userinfo = userInfo;
        this.cache.userinfo.password = this.cache.upwd;
        this.jupushInit();
        this.dataservice.getProjectlistByCompanyId(results[2].data[0].companyId, userInfo.userId).subscribe(resp => {
          this.cache.projects = resp.data;
          this.cache.currentProject = resp.data[0];
          this.showAD();
        });
      }
    });

  }

  /**
   * 显示广告
   */
  async showAD() {
    console.log('登录默认首页', this.cache.getCurrentIndexPage())
    const adModal = await this.modalCtrl.create({
      component: ADModal,
      componentProps: { url: 'http://assets.tomatobang.com/loginad.mp4' }
    });
    await adModal.present().then(() => {
      this.router.navigate(['/tabs/' + this.cache.getCurrentIndexPage()]);
    });
  }


  /**
   * 获取短信验证码
   */
  getSMSCode() {
    if (this.couldSendSMSCode) {
      if (this.verifyCellphone(this.sms.cellphone)) {
        this.couldSendSMSCode = false;
        this.setSMSTimeout();
        this.dataservice.getSMSVerifyCode(this.sms.cellphone).subscribe(ret => {
          if (ret.success) {
            this.presentToast('短信验证码发送成功');
          } else {
            if (ret.message.length > 40) {
              this.error = ret.message.substring(0, 41) + '...';
            } else {
              this.error = ret.message;
            }
          }
        });
      } else {
        this.presentToast('请填写正确的手机号码!');
      }
    } else {
      this.presentToast('暂时不能发送短信验证码!');
    }
  }

  /**
   * 获取短信验证码时间限制
   */
  setSMSTimeout() {
    let timeout = 60;
    const SMSTimeoutInterval = setInterval(() => {
      if (timeout > 0) {
        timeout -= 1;
        this.getSMSCodeText = timeout + '';
      } else {
        this.couldSendSMSCode = true;
        this.getSMSCodeText = '获取验证码';
        clearInterval(SMSTimeoutInterval);
      }
    }, 1000);
  }

  /**
   * 验证手机号是否正确
   * @param cellphone 手机号
   */
  verifyCellphone(cellphone) {
    const reg = new RegExp(/^1[34578]\d{9}$/);
    if (reg.test(cellphone)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 键盘输入时清除错误
   */
  onKeyPressed() {
    this.error = '';
  }

  /**
   * 弹出提示消息
   * @param msg 消息
   */
  async presentToast(msg) {
    const toast = await this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'top',
    });
    await toast.present();

    const { data } = await toast.onDidDismiss();
    console.log(data);
  }

  /**
   * 切换登录方式
   */
  switchLoginWay() {
    this.error = '';
    this.phoneLogin = !this.phoneLogin;
  }

  async initPassward() {
    console.log(this.cache.upwd);
    this.error = '';
    const datas = {
      index: 3,
      value: {},
    };
    const modal = await this.modalCtrl.create({
      component: UserInfoModal,
      componentProps: { datas: datas }
    });
    modal.present();
  }

  // 极光初始化服务
  jupushInit() {
    console.log(this.cache.userinfo.userId)
    this.jpush.init();
    this.jpush.setDebugMode(true);
    console.log('极光设置', this.cache.jpushstate);
    if (!this.cache.jpushstate || this.cache.jpushstate === '1' || this.cache.jpushstate === '') {
      console.log('进入极光');
      this.jpush.setAlias({
        sequence: new Date().getTime(),
        alias: this.cache.userinfo.userId.toString(),
      }).then((args) => {
        console.log('极光设置成功', args);
      }).catch(err => {
        console.log('极光设置失败', err);
        if (window.cordova) {
          this.jupushInit();
        }
      });
    }
  }

}

